package vn.bk.hotel.adapter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Facebook.DialogListener;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import vn.bk.hotel.DetailHotel;
import vn.bk.hotel.MainMenuActivity;
import vn.bk.hotel.R;
import vn.bk.hotel.SplashScreen;
import vn.bk.hotel.object.HotelInfo;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.RatingBar;
import android.widget.TextView;

public class ListHotelAdapter extends BaseAdapter {
    private LayoutInflater inflater;

    private ArrayList<HotelInfo> myListResult;
    private Activity mContext;
    ImageLoader imageLoader;
    DisplayImageOptions options;
    private SharedPreferences sp;
    private DatabaseHotel myDB;

    public ListHotelAdapter(Activity context, ArrayList<HotelInfo> array) {
	mContext = context;
	this.myListResult = array;
	inflater = (LayoutInflater) context
		.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	imageLoader = ImageLoader.getInstance();
	imageLoader.init(ImageLoaderConfiguration.createDefault(mContext));

	options = new DisplayImageOptions.Builder()
		.showStubImage(R.drawable.ic_stub)
		.showImageForEmptyUri(R.drawable.ic_empty)
		.showImageOnFail(R.drawable.ic_empty).cacheInMemory()
		.cacheOnDisc().displayer(new RoundedBitmapDisplayer(0)).build();

	myDB = new DatabaseHotel(context);

    }

    @Override
    public int getCount() {
	// TODO Auto-generated method stub
	return myListResult.size();
    }

    public ArrayList<HotelInfo> getListHotel() {
	return this.myListResult;
    }

    @Override
    public Object getItem(int arg0) {
	// TODO Auto-generated method stub
	return null;
    }

    @Override
    public long getItemId(int position) {
	// TODO Auto-generated method stub
	return 0;
    }

    public void addItem(HotelInfo h) {
	this.myListResult.add(h);
    }

    public void clear() {
	this.myListResult = new ArrayList<HotelInfo>();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

	ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
	HotelHolder hHolder = new HotelHolder();
	if (convertView == null) {
	    convertView = inflater.inflate(R.layout.item_row_result, null);
	    hHolder.name = (TextView) convertView.findViewById(R.id.nameHotel);
	    // hHolder.address = (TextView)
	    // convertView.findViewById(R.id.address);
	    // hHolder.type = (TextView) convertView.findViewById(R.id.type);
	    hHolder.address = (TextView) convertView
		    .findViewById(R.id.address_hotel);
	    // hHolder.facebook = (ImageView) convertView
	    // .findViewById(R.id.img_fb);
	    // hHolder.favorite = (ImageView) convertView
	    // .findViewById(R.id.img_favorite);
	    hHolder.ratingBar = (RatingBar) convertView
		    .findViewById(R.id.ratingbar);
	    hHolder.viewImage = (ImageView) convertView
		    .findViewById(R.id.image_hotel);
	    hHolder.distance = (TextView) convertView
		    .findViewById(R.id.distance);
	    hHolder.noranking = (TextView) convertView
		    .findViewById(R.id.no_ranking);
	    // hHolder.call = (ImageView)
	    // convertView.findViewById(R.id.img_call);
	    hHolder.subMenu = (ImageView) convertView
		    .findViewById(R.id.img_sub_menu);
	    convertView.setTag(hHolder);
	}

	final HotelInfo h = myListResult.get(position);
	if (h != null) {
	    final HotelHolder hHolderInfo = (HotelHolder) convertView.getTag();
	    hHolderInfo.name.setText(h.getNameHotel());
	    // hHolderInfo.type.setText(h.getType());
	    // hHolderInfo.address.setText(h.getAdress());
	    if (h.getNumRate() > 0) {
		hHolderInfo.ratingBar.setVisibility(RatingBar.VISIBLE);
		hHolderInfo.noranking.setVisibility(TextView.GONE);
		hHolderInfo.ratingBar.setRating(h.getNumRate());
	    } else {
		hHolderInfo.ratingBar.setVisibility(RatingBar.GONE);
		hHolderInfo.noranking.setVisibility(TextView.VISIBLE);
	    }
	    hHolderInfo.address.setText(h.getAdress().subSequence(0, 30)
		    + "...");
	    // hHolder.viewImage.setLayoutParams(new LayoutParams(100, 100));
	    Log.i("URL bitmap hotel", h.getUrlBitMapHotel());

	    imageLoader.displayImage(h.getUrlBitMapHotel(),
		    hHolderInfo.viewImage, options, animateFirstListener);
	    // if (h.getPhone().equals("anyType{}") || h.getPhone() == null
	    // || h.getPhone().equals("")) {
	    // hHolderInfo.call.setVisibility(ImageView.INVISIBLE);
	    // } else {
	    // hHolderInfo.call.setVisibility(ImageView.VISIBLE);
	    // }

	    // if (myDB.isExistInDatabase(h)) {
	    // hHolderInfo.favorite.setImageResource(R.drawable.bt_favor);
	    // } else {
	    // hHolderInfo.favorite.setImageResource(R.drawable.add_favorite);
	    // }

	    final PopupMenu popupSort = new PopupMenu(mContext,
		    hHolderInfo.subMenu);
	    if (myDB.isExistInDatabase(h)) {
		popupSort.inflate(R.menu.sub_menu_detail_added_favor);
	    } else {
		popupSort.inflate(R.menu.sub_menu_detail);
	    }

	    hHolderInfo.subMenu.setOnClickListener(new OnClickListener() {

		@Override
		public void onClick(View v) {
		    // TODO Auto-generated method stub
		    popupSort.show();
		}
	    });

	    popupSort.setOnMenuItemClickListener(new OnMenuItemClickListener() {

		@Override
		public boolean onMenuItemClick(MenuItem item) {

		    switch (item.getItemId()) {
		    case R.id.sub_add_favorite:
			myDB.createHotel(h);
			popupSort.getMenu().clear();
			popupSort.inflate(R.menu.sub_menu_detail_added_favor);
			break;
		    case R.id.sub_facebook:
			loginFacebookAndShare(h);
			break;
		    case R.id.sub_remove_favorite:
			myDB.deleteHotel(h);
			popupSort.getMenu().clear();
			popupSort.inflate(R.menu.sub_menu_detail);
			break;
		    }
		    return true;
		}
	    });


	    if (h.isLocation()) {
		float[] results = new float[1];
		Location.distanceBetween(SplashScreen.latitude,
			SplashScreen.longtitude, h.getLatitude(),
			h.getLongitude(), results);

		hHolderInfo.distance.setText(String.format("%.2f km",
			results[0] / 1000));
		h.setRadius(results[0] / 1000);
	    } else
		hHolderInfo.distance.setVisibility(TextView.GONE);

	    // hHolderInfo.call.setOnClickListener(new OnClickListener() {
	    //
	    // @Override
	    // public void onClick(View v) {
	    // // TODO Auto-generated method stub
	    //
	    // Intent localIntent = new Intent(
	    // "android.intent.action.DIAL", Uri.parse("tel:"
	    // + h.getPhone()));
	    // mContext.startActivity(localIntent);
	    //
	    // }
	    // });
	    // hHolderInfo.facebook.setOnClickListener(new OnClickListener() {
	    //
	    // @Override
	    // public void onClick(View v) {
	    // // TODO Auto-generated method stub
	    // // hotelShare = h;
	    // loginFacebookAndShare(h);
	    // // View vs = inflater.inflate(R.drawable.pink_bg, null);
	    // // quickActionPopup.show(v);
	    // }
	    // });
	    // hHolderInfo.favorite.setOnClickListener(new OnClickListener() {
	    //
	    // @Override
	    // public void onClick(View v) {
	    // if (myDB.isExistInDatabase(h)) {
	    // hHolderInfo.favorite
	    // .setImageResource(R.drawable.add_favorite);
	    // myDB.deleteHotel(h);
	    // } else {
	    // hHolderInfo.favorite
	    // .setImageResource(R.drawable.bt_favor);
	    // myDB.createHotel(h);
	    // }
	    // }
	    // });
	    convertView.setOnClickListener(new OnClickListener() {

		@Override
		public void onClick(View v) {
		    // TODO Auto-generated method stub
		    DetailHotel.hotel = h;

		    mContext.startActivity(new Intent(mContext,
			    DetailHotel.class));
		}
	    });
	}

	return convertView;
    }

    @SuppressWarnings({ "deprecation" })
    private void loginFacebookAndShare(final HotelInfo myBus) {
	final Facebook facebook = new Facebook(
		mContext.getString(R.string.app_id));

	sp = ((Activity) mContext).getPreferences(0);
	String access_token = sp.getString("access_token", null);
	long expire = sp.getLong("access_expire", 0);
	if (access_token != null) {
	    facebook.setAccessToken(access_token);
	}
	if (expire != 0) {
	    facebook.setAccessExpires(expire);
	}
	if (facebook.isSessionValid()) {
	    postToFacebook(myBus, facebook);
	} else {
	    String[] permissions = { "" };

	    facebook.authorize((Activity) mContext, permissions,
		    IGNORE_ITEM_VIEW_TYPE, new DialogListener() {

			@Override
			public void onFacebookError(FacebookError e) {
			    // TODO Auto-generated method stub

			}

			@Override
			public void onError(DialogError e) {
			    // TODO Auto-generated method stub

			}

			@SuppressLint("CommitPrefEdits")
			@Override
			public void onComplete(Bundle values) {
			    // TODO Auto-generated method stub
			    postToFacebook(myBus, facebook);
			    Editor editor = sp.edit();
			    editor.putString("access_token",
				    facebook.getAccessToken());
			    editor.putLong("access_expire",
				    facebook.getAccessExpires());
			    editor.commit();
			}

			@Override
			public void onCancel() {
			    // TODO Auto-generated method stub

			}
		    });
	}

    }

    @SuppressWarnings("deprecation")
    private void postToFacebook(HotelInfo myHotelShare, Facebook facebook) {

	Bundle paramas = new Bundle();
	paramas.putString("caption", myHotelShare.getNameHotel());
	paramas.putString("description", myHotelShare.getDescription());
	paramas.putString("link", myHotelShare.getUri());
	paramas.putString("picture", myHotelShare.getBitMapUrl());

	facebook.dialog(mContext, "feed", paramas, new DialogListener() {

	    public void onFacebookError(FacebookError e) {
		// TODO Auto-generated method stub

	    }

	    public void onError(DialogError e) {
		// TODO Auto-generated method stub

	    }

	    public void onComplete(Bundle values) {
		// TODO Auto-generated method stub

	    }

	    public void onCancel() {
		// TODO Auto-generated method stub

	    }
	});
    }

    public static class AnimateFirstDisplayListener extends
	    SimpleImageLoadingListener {

	static final List<String> displayedImages = Collections
		.synchronizedList(new LinkedList<String>());

	@Override
	public void onLoadingComplete(String imageUri, View view,
		Bitmap loadedImage) {
	    if (loadedImage != null) {
		ImageView imageView = (ImageView) view;
		boolean firstDisplay = !displayedImages.contains(imageUri);
		if (firstDisplay) {
		    FadeInBitmapDisplayer.animate(imageView, 600);
		    displayedImages.add(imageUri);
		}
	    }
	}
    }

    class HotelHolder {
	TextView name, distance, type, address, noranking;
	RatingBar ratingBar;
	ImageView viewImage, facebook, favorite, subMenu;
	ImageView call;
    }

}
